﻿using System;
using System.Collections.Generic;
using System.IO;
using CoTime.DataAccess;
using CoTime.Model;

namespace CoTime.ViewModel
{
    public class MainWindowViewModel:ViewModelBase
    {
        #region [ Fields ]

        readonly Repository<Task> _taskRepository;
        readonly Repository<Note> _noteRepository;

        public List<Task> Tasks
        {
            set 
            {
                _taskRepository.SetItem(value);
            }
            get
            {
                return _taskRepository.GetItems();
            } 
        }

        public List<Note> Notes
        {
            set
            {
                _noteRepository.SetItem(value);
            }
            get
            {
                return _noteRepository.GetItems();
            }
        }

        #endregion

        #region [ Constructor ]

        public MainWindowViewModel(String taskFile)
        {
            String directory = Path.GetDirectoryName(taskFile);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            _taskRepository = new Repository<Task>(taskFile);
            _noteRepository = new Repository<Note>(Path.Combine(Config.DataPath,"Data/Notes.xml"));
        }

        #endregion // Constructor

        #region [ Methods ]

        public void Save()
        {
            if (Tasks != null && Tasks.Count > 0)
            { 
                _taskRepository.SetItem(Tasks);
                _taskRepository.Save();
            }
            if (Notes != null && Notes.Count > 0)
            {
                _noteRepository.SetItem(Notes);
                _noteRepository.Save();
            }
        }

        #endregion

        public List<Task> GetTasks(DateTime dt)
        {
            if (dt == null)
                throw new ArgumentNullException("you can't get tasks ");
            if (dt.Date.Equals(DateTime.Today.Date))
                return this.Tasks;
            List<Task> tasks = new List<Task>();
            String taskFile = dt.GetTaskFile();
            if (File.Exists(taskFile))
            { 
                Repository<Task> taskRepository = new Repository<Task>(taskFile);
                tasks = taskRepository.GetItems();
            }
            return tasks;
        }
    }
}
